<template>
	<el-upload :action="uploadImgUrl" :file-list="fileList" v-bind="uploadConfig">
		<el-button type="primary" size="small" solt="trigger">选择文件</el-button>
		<div slot="tip" class="el-upload__tip">
			只能上传
			<font color="red">{{ fileType.join() }}</font>
			文件，且不超过
			<font color="red">{{ fileSize }}MB</font>
		</div>
	</el-upload>
</template>

<script>
import { getToken } from '@/utils/auth';
import emitter from 'element-ui/src/mixins/emitter';
export default {
	mixins: [emitter],
	props: {
		fileSize: { type: Number, default: 5 },
		value: { type: Array, default: () => [] },
		fileType: { type: Array, default: () => ['doc', 'docx', 'pdf'] }
	},
	data() {
		return {
			fileList: this.value,
			uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
			uploadConfig: {
				limit: 1,
				ref: 'upload',
				multiple: false,
				class: 'duty_book_uploader',
				onExceed: this.handleExceed,
				onSuccess: this.handleUploadSuccess,
				beforeUpload: this.handleBeforeUpload,
				accept: this.fileType.map((n) => `.${n}`).join(),
				headers: { Authorization: 'Bearer ' + getToken() }
			}
		};
	},
	watch: {
		value(arr) {
			this.fileList = arr;
		},
		fileList(arr) {
			this.$emit('input', arr);
			this.dispatch('ElFormItem', 'el.form.change', [arr]);
		}
	},
	methods: {
		// 上传前loading加载
		handleBeforeUpload(file) {
			let isImg = false;
			if (this.fileType.length) {
				let fileExtension = '';
				if (file.name.lastIndexOf('.') > -1) {
					fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
				}
				isImg = this.fileType.some((type) => {
					if (file.type.indexOf(type) > -1) return true;
					if (fileExtension && fileExtension.indexOf(type) > -1) return true;
					return false;
				});
			} else {
				isImg = file.type.indexOf('image') > -1;
			}

			if (!isImg) {
				this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`);
				return false;
			}
			if (this.fileSize) {
				const isLt = file.size / 1024 / 1024 < this.fileSize;
				if (!isLt) {
					this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
					return false;
				}
			}
			this.$modal.loading('正在上传图片，请稍候...');
		},
		// 文件个数超出
		handleExceed() {
			this.$modal.msgError(`上传文件数量不能超过 ${this.uploadConfig.limit} 个!`);
		},
		// 上传成功回调
		handleUploadSuccess(res, file) {
			this.$modal.closeLoading();
			if (res.code === 200) {
				let title = res.originalFilename;
				let suffix = title.split('.').pop();
				let name = title.slice(0, -(suffix.length + 1));
				this.fileList.push({ name, suffix, url: res.url, size: file.size });
			}
		}
	}
};
</script>
<style lang="scss" scoped>
.duty_book_uploader::v-deep {
}
</style>
